package com.xyzk.diagnose.activity.other;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import android.os.Handler;
import android.util.Log;

import com.xyzk.diagnose.R;
import com.xyzk.diagnose.httputils.HttpRequest;
import com.xyzk.diagnose.httputils.ServerSocket;
import com.xyzk.diagnose.tools.Common;
import com.xyzk.diagnose.tools.Commonfunc;
import com.xyzk.diagnose.tools.DbAdapter;
import com.xyzk.diagnose.tools.DbAdapter.TableMain;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SettingQueryThread {
	public List<Map<String, String>> uplist;
	private List<Map<String, String>> detailList;
	private ServerSocket server;
	private Handler handler;
	private String vin;
	public boolean isShow ;
	public int uploading;//正在上传的数据下标


	/**
	 * 设置处理对象
	 * @param handler
	 */
	public void setHandler(Handler handler){
		this.handler = handler;
	}


	/**
	 * 查询数据库线程
	 */
	public class SQLiteThread extends Thread{
		private String where;
		private String[] whereArg;

		public SQLiteThread(String where,String[] whereArg){
			this.where = where;
			this.whereArg = whereArg;
		}

		@Override
		public void run() {
			DbAdapter db = new DbAdapter();
			db.open();
			uplist = db.queryMainTable(where, whereArg);
			if(uplist == null){
				handler.sendEmptyMessage(Common.UPLOAD_DATA_NULL);
			}else{
				handler.sendEmptyMessage(Common.UPLOAD_DATA);
			}
			db.close();

		}
	}

	/**
	 * 上传数据线程
	 */
	public class UploadThread extends Thread{
		private int pos = -1;//小于0上传所有数据，大于0上传单条数据

		public UploadThread(){
		}

		public UploadThread(int pos){
			this.pos = pos;
		}

		@Override
		public void run() {
			if(uplist == null) return;
			DbAdapter db = new DbAdapter();
			db.open();
			server = new ServerSocket();
			if(server.connectServer(Common.serverIP, Common.serverPort)){
				if(pos < 0){//批量数据上传
					int k = 0;
					for(int i = 0; i < uplist.size(); i ++){
						uploading = i;
						// 选择未上传的数据上传
						Map map = uplist.get(i);
						if ("未上传".equals(map.get(TableMain.update))||map.get(TableMain.update)==null){
							k++;
							uploadData(i, db);
						}
					}
					if (k!=0){
						handler.sendEmptyMessage(Common.UPLOAD_DATA_AGO);
					}
				}else{//单条数据上传
					uploadData(pos, db);
				}
			}else{
				handler.sendEmptyMessage(Common.UPLOAD_DATA_FAILED);
			}
			server.close();
			db.close();
		}

		/**
		 * 选择上传数据
		 * @param pos 数据下标
		 */
		private void uploadData(int pos, DbAdapter db){
			// todo 根据新的数据库表定义新的上传规则
			String mes = uplist.get(pos).get(TableMain.update);
			vin = uplist.get(pos).get(TableMain.vin);
//			//先上传PC
//			if("已上传".equals(pc)){//都已上传
//				handler.sendEmptyMessage(Common.UPLOAD_DATA_AGO);
//			}else{
//				detailList = db.queryDataFromTable(vin);
//				sendDataToDbAndPrint(pos);
//			}
//			//mes
//			if(mes == null || "未上传".equals(mes))
//			{
//				detailList = db.queryDataFromTable(vin);
//				sendDataToMesOBD(pos);
//			}
//			else
//			{
//				handler.sendEmptyMessage(Common.UPLOAD_DATA_AGO);
//			}

			if(mes == null || "未上传".equals(mes)){
				detailList = db.queryDataFromTable(vin);  //查询需要上传的数据
				//上传服务器
				SendWebData(uplist.get(pos),detailList);
				//上传成功后，修改数据库状态
				if (Common.updata_isok==true){
					db.updatemaintable(Integer.parseInt(uplist.get(pos).get(TableMain.ID)));
					//传入界面进行更新
					handler.sendEmptyMessage(Common.UPLOAD_DATA_SUCCESS);
				}
			}else if ("已上传".equals(mes)){
				handler.sendEmptyMessage(Common.UPLOAD_DATA_AGO);
			}
			Commonfunc.sleep(100);
		}

//		/**
//		 * 数据上传到上位机并打印
//		 * @param pos 选择的数据
//		 */
//		private void sendDataToDbAndPrint(int pos){
//			String result = uplist.get(pos).get(TableMain.printdata);
//
//			server.sendDataToServer(Commonfunc.getByteLenOfFive(result));
//			Commonfunc.sleep(Common.DIALOG_WAIT_TIME);//上传详细数据
//			String detailData = "5:" + detailList.size() + ":" + vin+ ";" +  detailList.toString();
//			server.sendDataToServer(Commonfunc.getByteLenOfFive(detailData));
//			Commonfunc.sleep(Common.DIALOG_WAIT_TIME);
//			handler.sendEmptyMessage(Common.UPLOAD_DATA_SUCCESS);
//			updateSQLite(TableMain.update, "已上传", uplist.get(pos).get(TableMain.ID));
//		}

		// 上传数据
		private void SendWebData(Map mainmap,List sublist) {
			//上传web服务器
			if(Common.web_enable  == true)
			{
				JSONObject jsonmain = new JSONObject();
				try {
					jsonmain.put("resultVin",mainmap.get(DbAdapter.TableMain.vin));
					jsonmain.put("resultCar",mainmap.get(DbAdapter.TableMain.car));
					jsonmain.put("resultCartype",mainmap.get(DbAdapter.TableMain.cartype));
					jsonmain.put("resultStation",mainmap.get(DbAdapter.TableMain.carstation));
					jsonmain.put("resultCarname",mainmap.get(DbAdapter.TableMain.carname));
					jsonmain.put("resultCardate",mainmap.get(DbAdapter.TableMain.timestart));
					jsonmain.put("resultCartime",mainmap.get(DbAdapter.TableMain.timeend));
					jsonmain.put("resultDevice",mainmap.get(DbAdapter.TableMain.device));
					jsonmain.put("resultPrintnum",mainmap.get(DbAdapter.TableMain.printnum));
					jsonmain.put("resultTestnum",mainmap.get(DbAdapter.TableMain.testnum));
					jsonmain.put("resultResult",mainmap.get(DbAdapter.TableMain.result));
					jsonmain.put("resultPrint",mainmap.get(DbAdapter.TableMain.printdata));
					jsonmain.put("resultPin",mainmap.get(DbAdapter.TableMain.pin));
					jsonmain.put("resultEsk",mainmap.get(DbAdapter.TableMain.esk));

					jsonmain.put("resultAppver",R.string.Mainactivity_title);
					//未启用
					jsonmain.put("resultColor","");
					jsonmain.put("resultUp2mes","0");
					jsonmain.put("resultUser","test");

					jsonmain.put("fileName",mainmap.get(DbAdapter.TableMain.logfileName));
					jsonmain.put("resultLog",mainmap.get(DbAdapter.TableMain.logpath));
					JSONArray array=new JSONArray();
					for(int k = 0; k < sublist.size(); k ++)
					{

						Map submap = (Map) sublist.get(k);
						JSONObject jsondetail = new JSONObject();
						jsondetail.put("mVin",mainmap.get(DbAdapter.TableMain.vin));
						jsondetail.put("mTestcode",submap.get(DbAdapter.TableData.testcode));
						jsondetail.put("mContext",submap.get(DbAdapter.TableData.context));
						jsondetail.put("mTestdata",submap.get(DbAdapter.TableData.testdata));
						jsondetail.put("mStand",submap.get(DbAdapter.TableData.stand));
						jsondetail.put("mResult",submap.get(DbAdapter.TableData.result));
						array.put(k,jsondetail);
					}
					jsonmain.put("tableResultDetails", array);
					Long v_upfileid = (long) 0;
					for(int k = 0; k < 3; k ++)
					{
						String res = HttpRequest.sendPostToMyMes(Common.web_updata, jsonmain.toString().replace(">",""));
						if(res.indexOf("200") > 0) //ok
						{
							JSONObject resjson = new JSONObject(res);
							JSONObject son = resjson.getJSONObject("data");
							if(son != null)
								v_upfileid = son.getLong("resultId");
							break;
						}else {
							Common.updata_isok=false;
						}
					}
					//上传日志文件
					if(v_upfileid > 0) {
						uploadFiles(Common.web_API_File, (String) mainmap.get(DbAdapter.TableMain.logpath), v_upfileid);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		/**
		 * 文件上传线程
		 * @param uploadUrl
		 * @param filePaths
		 * @param id
		 */

		public void uploadFiles(String uploadUrl, String filePaths,Long id)
		{
			MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
			String fname = filePaths;
			File tempfile = new File(fname);
			//根据文件的后缀名，获得文件类型
			builder.setType(MultipartBody.FORM)
					.addFormDataPart("resultId", String.valueOf(id))// 其他参数信息
					.addFormDataPart( //给Builder添加上传的文件
							"files",  //请求的名字
							tempfile.getName(), //文件的文字，服务器端用来解析的
							RequestBody.create(MediaType.parse("multipart/form-data"), tempfile)//创建RequestBody，把上传的文件放入
					);
			MultipartBody requestBody = builder.build();
			Request request = new Request.Builder()
					.url(uploadUrl)
					.post(requestBody)
					.build();
			OkHttpClient client = new OkHttpClient.Builder()
					.connectTimeout(10000, TimeUnit.SECONDS)
					.readTimeout(10000, TimeUnit.SECONDS)
					.writeTimeout(10000, TimeUnit.SECONDS).build();
			client.newCall(request).enqueue(new Callback() {
				@Override
				public void onFailure(Call call, final IOException e) {
					Log.e("TAG", "返回内容===失败>:" + e.toString());
				}

				@Override
				public void onResponse(Call call, Response response) throws IOException {
					String result = response.body().string();
					Log.e("TAG", "返回内容===成功>:" + result);
				}
			});
		}

//		/**
//		 * 上传OBD数据
//		 * @param pos 选择的数据
//		 */
//		public void sendDataToMesOBD(int pos)
//		{
//			//TODO
//			//			final String result = uplist.get(pos).get(TableMain.MES_DATA);
//			//			String uploadResult="";//HttpRequest.uploadResult("saveEquipMentMessage","");
//			//			if("网络异常".equals(uploadResult)||uploadResult.contains(Common.NG)){
//			//				handler.sendEmptyMessage(Common.UPLOAD_DATA_FAILED);
//			//			}else{
//			//				handler.sendEmptyMessage(Common.UPLOAD_DATA_SUCCESS);
//			//				updateSQLite(TableMain.UPLOAD_MES,0,uplist.get(pos).get(TableMain.ID));
//			//			}
//			int v_req = 0x7E0;
//			int v_res = 0x7E8;
//			String vin="";
//			String obd="";
//			//int obd_num = 0;
//			String odo="3";
//			String emsModuleId="";
//			String emsName="";
//			String ems_calId1="";
//			String ems_calId2="";
//			String ems_calId3="";
//			String ems_cvn1="";
//			String ems_cvn2="";
//			String ems_cvn3="";
//			String tcuModuleId="";
//			String tcuName="";
//			String tcu_calId1="";
//			String tcu_calId2="";
//			String tcu_calId3="";
//			String tcu_cvn1="";
//			String tcu_cvn2="";
//			String tcu_cvn3="";
//			String opass="";
//			emsModuleId = String.format("%02X", v_req)+"/"+String.format("%02X", v_res);
//			tcuModuleId = "7E1/7E9";
//			//获取数据
//			for(int k = 0; k < detailList.size(); k ++)
//			{
//				String name = detailList.get(k).get(Common.TESTNAME);
//				if("读取EMS名称".equals(name))
//				{
//					emsName= detailList.get(k).get(Common.CONTENT);
//				}
//				else if("读取TCU名称".equals(name))
//				{
//					tcuName= detailList.get(k).get(Common.CONTENT);
//				}
//				else if("读取EMS CAL ID".equals(name))
//				{
//					ems_calId1= detailList.get(k).get(Common.CONTENT);
//				}
//				else if("读取TCU CAL ID".equals(name))
//				{
//					tcu_calId1= detailList.get(k).get(Common.CONTENT);
//				}
//				else if("读取EMS CVN".equals(name))
//				{
//					ems_cvn1= detailList.get(k).get(Common.CONTENT);
//				}
//				else if("读取TCU CVN".equals(name))
//				{
//					tcu_cvn1= detailList.get(k).get(Common.CONTENT);
//				}
//				else if("读取OBD要求".equals(name))
//				{
//					obd= detailList.get(k).get(Common.CONTENT);
//				}
//				else if("读取VIN码".equals(name))
//				{
//					vin = detailList.get(k).get(Common.CONTENT);
//				}
//			}
//
//
//			if("".equals(obd)||"".equals(odo)||"".equals(emsName)||"".equals(ems_calId1)||"".equals(ems_cvn1)){
//				opass="0";
//			}else if(tcuName.length() > 0 && ("".equals(tcuName)||"".equals(tcu_calId1)||"".equals(tcu_cvn1))){
//				opass="0";
//			}else{
//				opass="1";
//			}
//			String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//			String param="<root><vin>"+vin+"</vin><Type>01</Type><Result>ok</Result><OBDDataDetail><EMS><obd_VIN>"+
//					vin+"</obd_VIN><obd>"+obd+"</obd><odo>"+odo+"</odo><moduleID>"+emsModuleId+"</moduleID><ECUname>"+
//					emsName+"</ECUname><calID_01>"+ems_calId1+"</calID_01><calID_02>"+ems_calId2+"</calID_02><calID_03>"+
//					ems_calId3+"</calID_03><cvn_01>"+ems_cvn1+"</cvn_01><cvn_02>"+ems_cvn2+"</cvn_02><cvn_03>"+
//					ems_cvn3+"</cvn_03></EMS><TCU><moduleID>"+tcuModuleId+"</moduleID><ECUname>"+
//					tcuName+"</ECUname><calID_01>"+tcu_calId1+"</calID_01><calID_02>"+tcu_calId2+"</calID_02><calID_03>"+
//					tcu_calId3+"</calID_03><cvn_01>"+tcu_cvn1+"</cvn_01><cvn_02>"+tcu_cvn2+"</cvn_02><cvn_03>"+
//					tcu_cvn3+"</cvn_03></TCU><opass>"+opass+"</opass><otestdate>"+date+"</otestdate><O_created_author>CP8</O_created_author>"+
//					"<O_CarManuf>SYC-CB</O_CarManuf><O_Operation>CP8</O_Operation><O_Operator>CP8</O_Operator></OBDDataDetail></root>";
//
//
//			byte[] nul={0};//替换00乱码
//			if(param.contains(new String(nul))){
//				param=param.replace(new String(nul), "");
//			}
//			boolean isupok = false;
//			for(int kk = 0; kk < 3; kk ++)
//			{
//				String result=HttpRequest.uploadOBDToMes(param);
//				//stepName = "上传OBD数据";
//				if(result!=null&&result.contains("成功")){
//					//showProcessList("上传OBD成功",Common.OK);
//					isupok = true;
//					break;
//				}else{
//					//showTip("上传重试第" + (kk + 1) + "次...");
//				}
//			}
//			if(isupok == false)
//			{
//				handler.sendEmptyMessage(Common.UPLOAD_DATA_FAILED);
//				updateSQLite(TableMain.UPLOAD_MES,"未上传",uplist.get(pos).get(TableMain.ID));
//			}
//			else
//			{
//				handler.sendEmptyMessage(Common.UPLOAD_DATA_SUCCESS);
//				updateSQLite(TableMain.UPLOAD_MES,"已上传",uplist.get(pos).get(TableMain.ID));
//			}
//
//		}

//		/**
//		 * 更新本地数据库
//		 * @param tableName 列名
//		 * @param upload    是否上传标志位
//		 * @param position  数据位置
//		 */
//		private void updateSQLite(String columName,int upload, String position){
//			DbAdapter db = new DbAdapter();
//			db.open();
//			db.updateTableUpload(columName, upload, position);
//			db.close();
//		}
//		private void updateSQLite(String columName,String updata, String position){
//			DbAdapter db = new DbAdapter();
//			db.open();
//			db.updateTableUpload(columName, updata, position);
//			db.close();
//		}
	}
}
